<template>

</template>

<script setup>
import * as Cesium from 'cesium'
import { ref, onMounted } from 'vue'
import axios from 'axios'
import GridCell from './GridCell_v2.3.js'

// 存储所有无人机轨迹数据
const uavTrajectories = ref([])

async function initUavLineTest (Viewer) {

  Viewer.camera.flyTo({
    destination: Cesium.Cartesian3.fromDegrees(
      104.6766174,
      31.4984767,
      1000 // 稍微增加高度以获得更好的视角
    ),
    duration: 3, // 飞行时间，单位为秒
    complete: () => {
      console.log('已飞入到指定位置');
    }
  });


  // 初始化后绘制无人机轨迹
  const result = await loadUavLineJson()
  const trajectories = result.trajectories
  const allPointsByTime = result.allPointsByTime

  // 可在此处使用trajectories数据进行轨迹绘制
  // console.log(trajectories[0].coordinates, "无人机轨迹数据");
  console.log(trajectories, "trajectoriestrajectoriestrajectories");
  console.log(allPointsByTime, "按时间排序的所有点数据");

  // 获取前5个轨迹数据（如果存在的话）并转换为GridCell期望的格式
  const uav1 = trajectories.length > 0 ? trajectories[0].coordinates.map(coord => [coord.longitude, coord.latitude, coord.height]) : []
  const uav2 = trajectories.length > 1 ? trajectories[1].coordinates.map(coord => [coord.longitude, coord.latitude, coord.height]) : []
  const uav3 = trajectories.length > 2 ? trajectories[2].coordinates.map(coord => [coord.longitude, coord.latitude, coord.height]) : []
  const uav4 = trajectories.length > 3 ? trajectories[3].coordinates.map(coord => [coord.longitude, coord.latitude, coord.height]) : []
  const uav5 = trajectories.length > 4 ? trajectories[4].coordinates.map(coord => [coord.longitude, coord.latitude, coord.height]) : []

  console.log(uav3, "uav3");
  console.log("轨迹数据时间信息:", trajectories.length > 2 ? trajectories[2].coordinates.slice(0, 3) : "无数据");

  // 显示所有轨迹的基本信息
  trajectories.forEach((traj, index) => {
    if (traj.coordinates.length > 0) {
      console.log(`轨迹${index + 1} (${traj.name}): ${traj.totalPoints}个点, 时间范围: ${traj.coordinates[0].time} 到 ${traj.coordinates[traj.coordinates.length - 1].time}`)
    } else {
      console.log(`轨迹${index + 1} (${traj.name}): 无数据`)
    }
  })

  // // 只有当轨迹数据不为空时才创建GridCell
  // if (uav1.length > 0) {
  //   const gridCell1 = new GridCell(Viewer, uav1[0])
  //   gridCell1.loadGridDataJson(uav1, 'Green')
  // }

  // if (uav2.length > 0) {
  //   const gridCell2 = new GridCell(Viewer, uav2[0])
  //   gridCell2.loadGridDataJson(uav2, 'Red')
  // }

  // if (uav3.length > 0) {
  //   const gridCell3 = new GridCell(Viewer, uav3[0])
  //   gridCell3.loadGridDataJson(uav3, 'White')
  // }

  // if (uav4.length > 0) {
  //   const gridCell4 = new GridCell(Viewer, uav4[0])
  //   gridCell4.loadGridDataJson(uav4, 'Yellow')
  // }

  // if (uav5.length > 0) {
  //   const gridCell5 = new GridCell(Viewer, uav5[0])
  //   gridCell5.loadGridDataJson(uav5, 'DarkGreen')
  // }

  const allPoints = await getAllPointsByTimeForGrid()
  const gridCell = new GridCell(Viewer, allPoints[0])
  // gridCell.loadGridDataJson(allPoints, 'Green')
  // console.log(allPoints, "按时间排序的所有点数据");

  let index = 0
  setInterval(() => {
    if (index > allPoints.length - 1) {
      index = 0
    }
    const currentPoint = allPoints[index]
    // console.log(currentPoint, index, allPoints, "currentPoint");
    // gridCell.drawSingleBox(currentPoint, 'White')
    // gridCell.changeColor({
    //   position: currentPoint,
    //   color: 'White',
    //   isGridColor: true,
    //   mode: 1
    // })
    // Viewer.entities.add({
    //   position: Cesium.Cartesian3.fromDegrees(currentPoint[0], currentPoint[1], currentPoint[2]),
    //   point: {
    //     color: Cesium.Color.RED,
    //     pixelSize: 10,
    //   },
    //   label: {
    //     text: `${index}`,
    //   }
    // })
    index++
  }, 100)
}

// 获取按时间排序的所有轨迹点（一维数组）
async function getAllPointsByTime () {
  const result = await loadUavLineJson()
  return result.allPointsByTime
}

// 获取按时间排序的轨迹点，转换为GridCell期望的格式
async function getAllPointsByTimeForGrid () {
  const allPoints = await getAllPointsByTime()
  return allPoints.map(point => [point.longitude, point.latitude, point.height])
}

async function loadUavLineJson () {
  try {
    // 创建存储所有轨迹数据的数组
    const allTrajectories = []

    // 固定的json文件编号列表 (按照文件编号顺序)
    const jsonFileNumbers = [10, 12, 14, 18, 20, 24, 26, 28, 30, 32, 34, 36, 38]

    // 对每个json文件发起请求
    for (const number of jsonFileNumbers) {
      try {
        const res = await axios.get(`/json3/${number}.json`)

        if (res.data && res.data.data && res.data.data.flyDataVOs && res.data.data.flyDataVOs.length > 0) {
          // 提取飞行数据
          const flyData = res.data.data.flyDataVOs

          // 提取每个时间点的经纬度、高度和时间信息
          const coordinates = []

          // 查找各字段的索引
          const headers = flyData[0]
          const createTimeIndex = headers.indexOf('createTime')
          const longitudeIndex = headers.indexOf('longitude')
          const latitudeIndex = headers.indexOf('latitude')
          const heightIndex = headers.indexOf('height')

          // 从数据行中提取坐标信息（跳过表头）
          for (let i = 1; i < flyData.length; i++) {
            const row = flyData[i]
            const createTime = row[createTimeIndex]
            const longitude = parseFloat(row[longitudeIndex])
            const latitude = parseFloat(row[latitudeIndex])
            const height = parseFloat(row[heightIndex])

            // 过滤掉[0,0,0]坐标
            if (longitude === 0 && latitude === 0 && height === 0) {
              continue // 跳过[0,0,0]坐标
            }

            coordinates.push({
              longitude: longitude,  // 经度
              latitude: latitude,    // 纬度
              height: height,        // 高度
              time: createTime,      // 时间戳
              timestamp: new Date(createTime).getTime() // 用于排序的时间戳
            })
          }

          // 按时间顺序排序坐标点
          coordinates.sort((a, b) => a.timestamp - b.timestamp)

          // 验证时间排序是否正确
          let isTimeOrderCorrect = true
          for (let j = 1; j < coordinates.length; j++) {
            if (coordinates[j].timestamp < coordinates[j - 1].timestamp) {
              isTimeOrderCorrect = false
              break
            }
          }
          console.log(`文件 ${number}.json 时间排序${isTimeOrderCorrect ? '正确' : '错误'}`)

          // 将文件数据添加到轨迹数组中
          allTrajectories.push({
            name: `uav-${number}`,
            coordinates: coordinates,
            fileNumber: number,
            totalPoints: coordinates.length
          })

          console.log(`成功加载文件: uav-${number}.json, 包含 ${coordinates.length} 个坐标点`)
          if (coordinates.length > 0) {
            console.log(`时间范围: ${coordinates[0].time} 到 ${coordinates[coordinates.length - 1].time}`)
            // 显示前3个和后3个坐标点的时间信息
            const firstThree = coordinates.slice(0, 3).map(c => `${c.time} [${c.longitude.toFixed(6)}, ${c.latitude.toFixed(6)}, ${c.height.toFixed(1)}]`)
            const lastThree = coordinates.slice(-3).map(c => `${c.time} [${c.longitude.toFixed(6)}, ${c.latitude.toFixed(6)}, ${c.height.toFixed(1)}]`)
            console.log(`前3个点:`, firstThree)
            console.log(`后3个点:`, lastThree)
          }
        } else {
          // 没有数据的文件用空数组代替
          allTrajectories.push({
            name: `uav-${number}`,
            coordinates: [],
            fileNumber: number,
            totalPoints: 0
          })
          console.log(`文件 ${number}.json 无飞行数据，使用空数组`)
        }
      } catch (err) {
        // 文件加载失败也用空数组代替
        allTrajectories.push({
          name: `uav-${number}`,
          coordinates: [],
          fileNumber: number,
          totalPoints: 0
        })
        console.error(`无法加载文件 ${number}.json:`, err.message)
      }
    }

    // 按照文件编号顺序排序轨迹数组
    allTrajectories.sort((a, b) => a.fileNumber - b.fileNumber)

    // 更新引用数据
    uavTrajectories.value = allTrajectories

    console.log(`总共处理了 ${allTrajectories.length} 个文件`)
    console.log(`其中有数据的文件: ${allTrajectories.filter(t => t.totalPoints > 0).length} 个`)
    console.log(`空数据文件: ${allTrajectories.filter(t => t.totalPoints === 0).length} 个`)

    // 将所有轨迹数据按时间顺序组装成一维数组
    const allPointsByTime = []

    // 收集所有有数据的轨迹点
    allTrajectories.forEach(trajectory => {
      if (trajectory.coordinates.length > 0) {
        trajectory.coordinates.forEach(coord => {
          allPointsByTime.push({
            ...coord,
            source: trajectory.name,  // 添加来源文件信息
            fileNumber: trajectory.fileNumber
          })
        })
      }
    })

    // 按时间戳排序所有点
    allPointsByTime.sort((a, b) => a.timestamp - b.timestamp)

    console.log(`按时间排序的总点数: ${allPointsByTime.length}`)
    if (allPointsByTime.length > 0) {
      console.log(`整体时间范围: ${allPointsByTime[0].time} 到 ${allPointsByTime[allPointsByTime.length - 1].time}`)
      console.log(`时间跨度: ${((allPointsByTime[allPointsByTime.length - 1].timestamp - allPointsByTime[0].timestamp) / 1000 / 60).toFixed(2)} 分钟`)

      // 显示前5个和后5个点的信息
      const firstFive = allPointsByTime.slice(0, 5).map(p => `${p.time} [${p.longitude.toFixed(6)}, ${p.latitude.toFixed(6)}, ${p.height.toFixed(1)}] (${p.source})`)
      const lastFive = allPointsByTime.slice(-5).map(p => `${p.time} [${p.longitude.toFixed(6)}, ${p.latitude.toFixed(6)}, ${p.height.toFixed(1)}] (${p.source})`)
      console.log(`按时间排序的前5个点:`, firstFive)
      console.log(`按时间排序的后5个点:`, lastFive)
    }

    return {
      trajectories: allTrajectories,
      allPointsByTime: allPointsByTime
    }
  } catch (error) {
    console.error('加载无人机轨迹数据出错:', error)
    return {
      trajectories: [],
      allPointsByTime: []
    }
  }
}

defineExpose({
  initUavLineTest,
})
</script>

<style scoped lang="scss"></style>